#!/usr/bin/env python
# -*- coding: UTF-8 -*-
'''
@Project ：图灵学习 
@File    ：21.异步上下文管理器.py
@IDE     ：PyCharm 
@Author  ：ChenLiGao
@Date    ：2024-11-11 10:17
'''
import asyncio


# 数据库异步链接以及增删改查
class AsyncConetentManager(object):
    def __init__(self, conn=None):
        print(1)
        self.conn = conn

    async def do_something(self):
        print(3)
        return "模拟数据库异步增删改查操作"

    async def __aenter__(self):
        print(2)
        self.conn = await asyncio.sleep(2, result="数据库连接成功...")
        print(self.conn)
        return self

    async def __aexit__(self, exc_type, exc_val, exc_tb):
        print(4)
        result = await asyncio.sleep(1, result="数据库连接关闭,.......")
        print(result)

async def main():
    async with AsyncConetentManager() as acm:
        result = await acm.do_something()
        print("结果为：", result)

if __name__ == '__main__':
    asyncio.run(main())